const { exec, execSync } = require("child_process");
const inquirer = require("inquirer");
// 获取分支
function getCurrentBranch() {
  return new Promise((resolve, reject) => {
    exec("git branch", (error, stdout, stderr) => {
      if (error) {
        reject(`执行的错误: ${error}`);
        return;
      }
      if (stderr) {
        reject(`stderr: ${stderr}`);
        return;
      }

      // 输出分支列表
      const branches = stdout
        .trim()
        .split("\n")
        .map((line) => line.trim());
      branches.forEach((branch, index) => {
        if (branch.startsWith("*")) {
          // 当前分支会以*标记，去除这个标记
          branches[index] = branch.slice(1).trim();
        }
      });

      // 过滤掉空白分支名，只保留有效分支名
      const activeBranches = branches.filter((name) => name !== "");
      resolve(activeBranches);
    });
  });
}
// 选择分支
function selectBranches(branches) {
  return new Promise((resolve, reject) => {
    inquirer
      // @ts-ignore
      .prompt([
        {
          type: "list",
          name: `brancheName`,
          message: "请选择下载内容？",
          choices: branches,
        },
      ])
      .then((res) => {
        resolve(res.brancheName);
      });
  });
}
async function deploy() {
  let branches = await getCurrentBranch();
  let brancheName = await selectBranches(branches);
  execSync(`git checkout .`);
  execSync(`git checkout ${brancheName}`);
  execSync(`git pull`);
  execSync(`npm run build:prod`);
}
deploy();
